import { _decorator, Component, Node } from 'cc'
const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = MovingSceneBg
 * DateTime = Wed Feb 09 2022 18:38:20 GMT+0800 (中国标准时间)
 * Author = ashscc
 * FileBasename = MovingSceneBg.ts
 * FileBasenameNoExtension = MovingSceneBg
 * URL = db://assets/script/MovingSceneBg.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/en/
 *
 */

@ccclass('MovingSceneBg')
export class MovingSceneBg extends Component {
  @property(Node)
  bg01: Node = null
  @property(Node)
  bg02: Node = null

  private _bgSpeed = 10 //移动速度为10个像素点，可以调
  private _bgMovingRange = 90

  start() {
    this._init()
  }

  _init() {
    //初始化两块背景的位置
    this.bg01.setPosition(0, 0, 0)
    this.bg02.setPosition(0, 0, -this._bgMovingRange)
  }

  update(deltaTime: number) {
    this._movingBackgroundScene(deltaTime)
  }

  _movingBackgroundScene(deltaTime: number) {
    //两块背景向z正方向移动，这样飞机看起来是向前移动的
    this.bg01.setPosition(
      0,
      0,
      this.bg01.position.z + this._bgSpeed * deltaTime
    )
    this.bg02.setPosition(
      0,
      0,
      this.bg02.position.z + this._bgSpeed * deltaTime
    )

    //如果超出了限制范围则返回到另一张的尾部
    if (this.bg01.position.z > this._bgMovingRange) {
      this.bg01.setPosition(0, 0, this.bg02.position.z - this._bgMovingRange)
    } else if (this.bg02.position.z > this._bgMovingRange) {
      this.bg02.setPosition(0, 0, this.bg01.position.z - this._bgMovingRange)
    }
  }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/en/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/en/scripting/life-cycle-callbacks.html
 */
